package com.example.onlinetaxi.ui.activity.Driver.MainPage;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.CurrentFragment;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.IExchangeFragments;
import com.example.onlinetaxi.callback.IRefreshCallBack;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.MineActivities.DriverMineCarActivity;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.MineActivities.DriverMineWeeklyActivity;
import com.example.onlinetaxi.ui.activity.EditBasicInfoPage.EditBasicInfoActivity;
import com.example.onlinetaxi.ui.activity.HomePage.HomeActivity;
import com.example.onlinetaxi.ui.activity.MainPage.MainActivity;
import com.example.onlinetaxi.ui.activity.MainPage.MineActivities.MineChangePasswordActivity;
import com.example.onlinetaxi.ui.activity.MainPage.MineActivities.MineWeeklyActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.view.Dialog.LoadingDialog;
import com.example.onlinetaxi.view.Dialog.MyDialog;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;

import java.util.HashMap;
import java.util.Map;

public class DriverMineFragment extends Fragment {
    private View rootView;
    // 用户信息layout
    private LinearLayout basicInfoLayout;
    // 用户信息
    private static TextView nicknameTv;
    private TextView orderCountTv;
    private TextView passengerScore;
    private TextView useTimeTv;
    // 回调函数
    private IExchangeFragments iExchangeFragments;
    // 星星条
    private SimpleRatingBar ratingBar;
    // 按钮
    private Button exitBtn;
    // 请求信息
    private Map<String, String> map = new HashMap<>();
    // 请求数据
    private String score;
    private String numberOfUseDays;
    private String numberOfOrders;
    // 功能跳转选项
    private LinearLayout driverMineWeekly;
    private LinearLayout driverMineChangePassword;
    private LinearLayout driverMineCar;
    private LinearLayout driverMineOrder;
    // 车辆图片
    private ImageView car;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_driver_mine, container, false);

        initView();

        initEvent();

        // 关闭加载框
        DriverMainActivity.closeProgressDialog();

        return rootView;
    }

    private void initEvent() {
        // 添加退出按钮功能
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        basicInfoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击跳转到完善个人信息界面
                startActivity(new Intent(getActivity(), EditBasicInfoActivity.class));
            }
        });
        EditBasicInfoActivity.iRefreshCallBack = new IRefreshCallBack() {
            @Override
            public void refresh() {
                // 开启加载框
                LoadingDialog.showLoading(getActivity());

                // 刷新界面
                initView();

                // 关闭加载框
                LoadingDialog.stopLoading();
            }
        };
        driverMineWeekly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 开启加载框
                LoadingDialog.showLoading(getActivity(), "正在生成周报...");

                startActivity(new Intent(getActivity(), DriverMineWeeklyActivity.class));
            }
        });
        driverMineOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 生成加载框
                LoadingDialog.showLoading(getActivity(), "正在加载订单信息...");

                // 通过回调函数改变主页的fragment
                iExchangeFragments.exchangeFragment();
            }
        });
        driverMineChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到修改密码界面
                startActivity(new Intent(getActivity(), MineChangePasswordActivity.class));
            }
        });
        driverMineCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到修改车辆信息界面
                startActivity(new Intent(getActivity(), DriverMineCarActivity.class));
            }
        });
    }

    public void setiExchangeFragments(IExchangeFragments iExchangeFragments) {
        this.iExchangeFragments = iExchangeFragments;
    }

    private void showDialog() {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消，不操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击确认
                // 将手机号发送到后端，设置用户为未登录状态
                map.put("phone", LocalStorage.phone);

                if (LocalStorage.currentOrderId == null) {
                    // 向后端发送请求
                    OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "login", "exit");
                    // 用户退出成功
                    Toast.makeText(getActivity(), "您已安全退出登录！", Toast.LENGTH_SHORT).show();
                    // 跳转到登录界面
                    startActivity(new Intent(getActivity(), HomeActivity.class));
                    // 销毁本页面
                    getActivity().finish();
                    // 清除本地缓存
                    LocalStorage.clear();
                    CurrentFragment.currentFragment = null;
                } else {
                    // 用户退出失败,显示失败原因
                    Toast.makeText(getActivity(), "退出登录失败!您还有未完成的订单!", Toast.LENGTH_SHORT).show();
                }
            }
        };

        MyDialog.drawable = getContext().getDrawable(R.drawable.dialog_confirm_driver);

        // 显示提示框
        MyDialog.showInfoDialog(getActivity(), "您是否要退出登录？", "取消", onCancelClickListener, "确认", onConfirmClickListener);
    }

    private void initView() {
        // 布局
        basicInfoLayout = rootView.findViewById(R.id.driver_basic_info);
        // 输入框
        nicknameTv = rootView.findViewById(R.id.driver_nickname);
        orderCountTv = rootView.findViewById(R.id.driver_order_count);
        useTimeTv = rootView.findViewById(R.id.driver_use_time);
        passengerScore = rootView.findViewById(R.id.mine_driver_score);
        ratingBar = rootView.findViewById(R.id.mine_driver_ratingbar);
        // 按钮
        exitBtn = rootView.findViewById(R.id.driver_exit_btn);
        // 功能跳转
        driverMineWeekly = rootView.findViewById(R.id.driver_mine_weekly);
        driverMineChangePassword = rootView.findViewById(R.id.driver_mine_change_password);
        driverMineCar = rootView.findViewById(R.id.driver_mine_car);
        driverMineOrder = rootView.findViewById(R.id.driver_mine_order);
        // 车辆图片
        car = rootView.findViewById(R.id.driver_mine_car_img);
        car.setColorFilter(getResources().getColor(R.color.perfect_gray));

        getDriverInfo();

        String nickName = getNickName();
        nicknameTv.setText(nickName);

        ratingBar.setRating(Float.parseFloat(score));
        useTimeTv.setText("与您相遇的第" + numberOfUseDays + "天");
        orderCountTv.setText("累计完成订单" + numberOfOrders + "次");
        passengerScore.setText(score + "分");
    }

    private static String getNickName() {
        Map<String, String> map = new HashMap<>();
        map.put("phone", LocalStorage.phone);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "user", "getNickName");
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);
        return dataResponse.getData().get("nickname").toString();
    }

    private void getDriverInfo() {
        map.clear();
        map.put("phone", LocalStorage.phone);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "user", "getUserInfo");
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            score = dataResponse.getData().get("score").toString();
            numberOfUseDays = dataResponse.getData().get("numberOfUseDays").toString();
            numberOfOrders = dataResponse.getData().get("numberOfOrders").toString();
        }
    }
}